<template>
  <div class="main">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="用户名：" prop="name">
        {{ formData.name }}
      </el-form-item>
      <el-form-item label="密码：" required prop="password"> 
        <el-input v-model="formData.password" type="password" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="重复密码：" required prop="rePassword">
        <el-input v-model="formData.rePassword" type="password" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary">提交</el-button>
        <!-- <el-button @click="reset" type="primary">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { updateUser } from '@/api/user'
export default {
  data(){
    return {
      currentUser:{},
      formData:{
        name:'',
        password:'',
        rePassword:''
      },
      rules:{
        password:[
          { validator : this.validatePass, trigger : 'blur'}
        ],
        rePassword:[
          { validator : this.validateRePass, trigger : 'blur'}
        ],
      }
    }
  },
  created(){
    this.currentUser = this.$store.getters.currentUser
    this.formData.name = this.currentUser.name
  },
  methods:{
    async submit(){
      this.$refs.form.validate(async valid=>{
        if(valid){
          let res = await updateUser({
            id:this.currentUser.id,
            password:this.formData.password
          })
          if(res.code === 0){
            this.$message({
              type:'success',
              message:'请重新登录'
            })
            // 清除token
            this.$store.dispatch('user/resetToken')
            this.$router.push('/login')
          }
        }
      })
      
    },
    // reset(){
      // 不起作用，所以隐藏掉
    //   this.$refs.form.resetFileds()
    //   this.formData={
    //     name:'',
    //     password:'',
    //     rePassword:''
    //   }
    // },
    validatePass(rule,value,callback){
      if(value === ''){
        callback(new Error('密码不能为空'))
      } else if(value.length > 30) {
        callback(new Error('密码不能超过30个字符'))
      } else if (this.formData.rePassword !== ''){
        this.$refs.form.validateField('rePassword')
      }
      callback()
    },
    validateRePass(rule,value,callback) {
      
      if(value ===''){
        callback(new Error('请再一次输入密码'))
      }else if(value !== this.formData.password){
        callback(new Error('两次密码不相同'))
      }
      callback()
    },

  }
}
</script>
<style lang="scss" scoped>
.main{
  padding:20px;
}
</style>

